//
//  SZLSearchViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/7/20.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLSearchViewController.h"
#import "SZLNavigationController.h"
#import "HomeNetService.h"
#import "NormalShopTableViewCell.h"
#import <MJRefresh.h>
#import "MBProgressHUD+MJ.h"
#import "ConGoodsDetailController.h"
#import "AddGoodsModel.h"
#import "ShoppingMallsCell.h"

@interface SZLSearchViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,SZLNavigationControllerDelegate>

@property (nonatomic,weak) UITextField *search;
@property (nonatomic,strong) UITableView *sourceTab;
@property (nonatomic,strong) NSMutableArray *sources;
@property (nonatomic,assign) NSInteger curPage;

@end

@implementation SZLSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNav];
    [self setTableView];
}

- (void)setNav
{
    UITextField *search = [[UITextField alloc]initWithFrame:CGRectMake(45, 27, ScreenW-60, 30)];
    search.borderStyle = UITextBorderStyleNone;
    search.layer.cornerRadius = 15.0;
    search.clipsToBounds = YES;
    search.placeholder = @"输入您想要的商品";
    search.backgroundColor = [UIColor whiteColor];
    UIImageView *leftImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 25)];
    leftImage.image = [UIImage imageNamed:@"searchbar_textfield"];
    leftImage.contentMode = UIViewContentModeRight;
    search.leftView = leftImage;
    search.leftViewMode = UITextFieldViewModeAlways;
    search.font = [UIFont systemFontOfSize:15];
    search.returnKeyType = UIReturnKeySearch;
    search.delegate = self;
    self.search = search;
    self.navigationItem.titleView = search;
    [search becomeFirstResponder];
}

- (void)setTableView
{
    [self.view addSubview:self.sourceTab];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sources.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingMallsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShoppingMallsCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.sources[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ConGoodsDetailController *goodsVc = [[ConGoodsDetailController alloc]init];
    NormalShopGoodsModel *model = self.sources[indexPath.section];
    goodsVc.productNo = model.productNo;
    [self.navigationController pushViewController:goodsVc animated:YES];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(NormalShopTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(void)viewDidLayoutSubviews
{
    if ([self.sourceTab respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.sourceTab setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.sourceTab respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.sourceTab setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.curPage = 1;
    [self searchGoodsList];
}
- (void)searchGoodsList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"name"] = self.search.text;
    parame[@"pageNo"] = @(self.curPage);
    [self showWaiter];
    [self hideNoDataView];
    [HomeNetService homeSearchWithParame:parame response:^(BOOL success, NSString *msg, NSArray *goods) {
        [self hideWaiter];
        [self.sourceTab.mj_header endRefreshing];
        [self.sourceTab.mj_footer endRefreshing];
        self.sourceTab.mj_footer.hidden = (goods.count>0)?YES:NO;
        if (success) {
            if (self.curPage == 1) {
                [self.sources removeAllObjects];
                if (goods.count == 0) {
                    [self showNoDataView:self.view.bounds];
                    return ;
                }
            }else {
                if (goods.count == 0) {
                    self.curPage--;
                    [self showOnlyText:@"暂无更多商品"];
                    return ;
                }
            }
            [self.sources addObjectsFromArray:goods];
            [self.sourceTab reloadData];
        }else{
            if ([msg isEqualToString:NoNetworkStatus]) {
                if (self.sources.count == 0) {
                    [self showRequestAgainView:@selector(searchGoodsList)];
                }
            }
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
        _sourceTab.dataSource = self;
        _sourceTab.delegate = self;
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([ShoppingMallsCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([ShoppingMallsCell class])];
        _sourceTab.rowHeight = 120;
        _sourceTab.tableFooterView = [[UIView alloc]init];
        _sourceTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.curPage = 1;
            [self searchGoodsList];
        }];
        _sourceTab.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.curPage++;
            [self searchGoodsList];
        }];
        _sourceTab.mj_footer.hidden = YES;
    }
    return _sourceTab;
}

//跟viewWillDisappear实现一个效果
- (BOOL)szlNavigationControllershouldPopItem:(SZLNavigationController *)navi
{
    [self.search resignFirstResponder];
    return YES;
}
- (NSMutableArray *)sources
{
    if (!_sources) {
        _sources = [NSMutableArray array];
    }
    return _sources;
}

@end
